Ext.ns('app.crud.user');
app.crud.user.canEdit = false;
app.crud.user.canDelete = false;

Ext.define('app.crud.user.ListModel', {
    extend: 'Ext.data.Model',
    fields: [
        {name:'id' , type:'integer'},
        {name:'group_id', type:'integer'},
        {name:'name' , type:'string'},
        {name:'login' , type:'string'},
        {name:'email' , type:'string'},
        {name:'enabled' , type:'boolean'},
        {name:'admin' , type:'boolean'},
        {name:'group_title' , type:'string'},
        {name:'registration_date', dateFormat: "Y-m-d H:i:s"} 	    
    ]
});

Ext.define('app.crud.user.GroupModel', {
    extend: 'Ext.data.Model',
    fields: [
         {name:'id' , type:'string'},
		 {name:'title' , type:'string'},
		 {name:'system' , type:'boolean'} 
    ]
});

Ext.define('app.crud.user.PermissionsModel', {
    extend: 'Ext.data.Model',
    fields: [
		{name:'id'  , type:'integer'},	
		{name:'user_id'  , type:'integer'},	
		{name:'group_id' , type:'integer'}, 	
		{name:'view', type:'boolean'},	
		{name:'edit', type:'boolean'}, 	
		{name:'delete', type:'boolean'},	
		{name:'publish', type:'boolean'},
		{name:'module' , type: 'string'},
		{name:'rc', type:'boolean'}
    ]
});

Ext.define('app.crud.user.Main',{
	extend:'Ext.tab.Panel',
	userList:null,
	groupsList:null,
	  
    constructor: function(config) {
		
		config = Ext.apply({
			deferredRender:true
	    }, config);		
		
		this.callParent(arguments);
	},
	initComponent:function(){
		this.activeTab= 0,
		this.deferredRender=false,
		this.title='Users::home',
		this.items=[
		       new app.crud.user.List({title:'Users'}),
		       new app.crud.user.Groups({title:'Groups'})
		];
		this.callParent(arguments);
	}
});


Ext.define('app.crud.user.List',{
	extend:'Ext.Panel',
	dataStore:null,
	dataGrid:null,
	searchField:null,
	saveButton:null,
   
   initComponent:function(){
	    this.layout = 'fit';
		this.dataStore = Ext.create('Ext.data.Store', {
		    model: 'app.crud.user.ListModel',
		    proxy: {
		        type: 'ajax',
		        url: app.root + 'userlist',
		        reader: {
		            type: 'json',
		            root: 'data',
		            totalProperty: 'count',
		            idProperty: 'id'
		        },
		        startParam:'pager[start]',
		        limitParam:'pager[limit]',
		        sortParam:'pager[sot]',
		        directionParam:'pager[dir]',
		        simpleSortMode: true
		    },
		    pageSize: 50,
	        remoteSort: true,
		    autoLoad: true,
		    sorters: [{
                 property : 'name',
                 direction: 'DESC'
           }]
		});
	
	   this.searchField =  new SearchPanel({store:this.dataStore,fieldNames:['login','name'],local:false});
		 
	   this.dataGrid = new Ext.grid.Panel({
			store: this.dataStore,
		    viewConfig:{
		    	stripeRows:true
		    },
           loadMask:true,
		    columnLines: true,
		    autoscroll:true,
		    frame: false,
		    defaults:{
		    	sortable:true
		    },
			tbar:[{
					text:'Add user',
					tooltip:'Add user',
					listeners:{
						click:{
							fn:function(){
								this.showEdit(0);
							},
							scope:this
						}
					}
				},'-','Account Type: ',
				{		    	
						displayField:"title",
						valueField:'id',
						queryMode:"local",
						triggerAction:"all",
						allowBlank: true,
						value:-1,
						width:150,
						emptyText:'All',
						xtype:"combo",
						name:'admin',
						forceSelection:true,								
						store:new Ext.data.Store({
							model:'app.comboModel',
							data:[
							      {id:-1 , title:'All'},
							      {id:1 , title:'Backend Users'},
							      {id:0 , title:'Frontend Users'}
							]
						}),
						listeners:{
							select:{
								fn:function(combo, record,  index ){
									this.dataStore.proxy.extraParams['filter['+combo.name+']']=  combo.getValue();
									this.dataStore.load();
								},
								scope:this
							}
						}
			    
				},'-','Status:',
				{		    	
					displayField:"title",
					valueField:'id',
					queryMode:"local",
					triggerAction:"all",
					allowBlank: true,
					value:-1,
					xtype:"combo",
					emptyText:'All',
					name:'enabled',
					forceSelection:true,								
					store:new Ext.data.Store({			
						model:'app.comboModel',
						data:[
						      {id:-1 ,title:'All'},
						      {id:1 , title:'Active'},
						      {id:0 , title:'Disabled'}
						]					
					}),
					width:100,
					listeners:{
						select:{
							fn:function(combo, record,  index ){
								this.dataStore.proxy.extraParams['filter['+combo.name+']']=  combo.getValue();
								this.dataStore.load();
							},
							scope:this
						}
					}
				},
				'->',this.searchField
			],
		    clicksToEdit:1,	    
		    columns: [
					{
					    text: 'Name',
					    dataIndex: 'name',
					    id:'name',
					    width:200,
					    align:'left',
					    sortable:true
					},{
						text: 'Group',
					    dataIndex: 'group_title',
					    width:200,
					    align:'left'
					},{
						text:'Login',
						dataIndex:'login',					
						align:'left',
						width:170,
						sortable:true				
		             },{
		            	text:'Email',
						dataIndex:'email',
						align:'left',
						width:170,
						sortable:true,
						enableKeyEvents:true
			         },{
			        	text: 'Backend Access',
					    dataIndex: 'admin',
					    width:90,
					    align:'center',
					    sortable:true,
					    renderer:app.checkboxRenderer
					},{
						text: 'Active',
					    dataIndex: 'enabled',
					    width:60,
					    align:'center',
					    id:'active',
					    sortable:true,
					    renderer:app.checkboxRenderer
					},{
						text:'',
			    	   	dataIndex:'id',
			    	   	id:'deleteColumn',
			    	   	width:40,
			    	   	align:'center',
			    	   	renderer:function(value, metaData, record, rowIndex, colIndex, store){
			    	   		if(!app.crud.user.canDelete || record.get('login')=='root'){
			    	   			return '';
			    	   		}else{
			    	   			return '<img src="/i/system/delete.gif" style="cursor:pointer;" title="Delete item">';
			    	   		}
			    	   	}
			       }
		    ],
		    bbar: Ext.create('Ext.PagingToolbar', {
	            store: this.dataStore,
	            displayInfo: true
	        })
	   	});
	   
	    this.dataGrid.on('cellclick', function(grid , item,  index, record, e, options){
			  var cellId = grid.getHeaderCt().getHeaderAtIndex(index).id;
			  if(cellId =='deleteColumn'){
				  this.removeUser(record);
			  } 
		},this);

	    this.dataGrid.on('itemdblclick',function(view , record){
			this.showEdit(record.get('id'));
		} ,this);
	   
	   	this.items = [this.dataGrid];
	   	
		this.callParent(arguments);
   },
   /**
    * Remove user Action
    * @param {Ext.dataRecord} id
    * @return void
    */
   removeUser:function(record){
	  var handle = this;
	  Ext.Ajax.request({
		  url: app.root + 'removeuser',
			method: 'post',
			waitMsg:'Saving...',
			params:{
				'id':record.get('id')
			},
	        success: function(response, request) {
				response =  Ext.JSON.decode(response.responseText);
				if(response.success){		
					handle.dataStore.remove(record);
				}else{
					Ext.MessageBox.alert('Message',response.msg);
				}	
	      }
		}); 	
   },
   showEdit:function(id){
	   var win = new  app.crud.user.Window({recordId:id});	   
	   win.on('dataSaved', function(){
		   this.dataStore.load();
	   },this);
	   
	   win.show();   
   }
});

/**
 * validationCache
 * @property {Object}
 */
app.crud.user.validationCacheUserName = {'id':'','val':''},

app.crud.user.Window = Ext.extend(Ext.Window,{
	/**
	 * Record form
	 * @property {Ext.form.FormPanel}
	 */
	dataForm:null,
	/**
	 * Additional request params
	 * @property {Object}
	 */
	extraParams:{},
	/**
	 * Record id
	 * @property integer
	 */
	recordId:0,
	/**
	 * Form fields config
	 * @property {Array}
	 */
	formFields: null,	
	/**
	 * Groups store
	 * @property {Ext.data.Store}
	 */
	goupsStore:null,
		
	constructor: function(config) {
		
		config = Ext.apply({
			modal: false,
	        layout:'fit',
	        width: 400,
	        height: 370,      
	        resizable:false,
	        plain:true,
			title:'Edit user'
	    },config);
		this.callParent(arguments);
	},
	initComponent:function(){
		
		this.groupsStore = new Ext.data.JsonStore({	
			autoLoad:true,
			model:'app.crud.user.GroupModel',
			proxy:{
				type:'ajax',
				url:app.root + 'grouplist',
				reader:{
					type:'json',
					root:'data'
				},
				simpleSortMode: true
			},
			root:'data',
			sorters: [{
			    field: 'title',
			    direction: 'ASC' // or 'DESC' (case sensitive for local sorting)
			}]
		});
		
		this.dataForm = new Ext.form.Panel({
			frame:false,
		    bodyCls:'formBody',
			border:false,
			bodyBorder:false,
			bodyPadding:5,		
			fieldDefaults:{
				anchor:"100%",
				labelAlign:'right',
				labelWidth:130
			},
			items:[{
				    	xtype:'hidden',
				    	name:'id',
				    	value:0
				    },{
				    	xtype:'checkbox',
				    	name:'admin',
				    	fieldLabel:'Is Administrator',
				    	value:0,
				    	inputValue:1,
				    	uncheckedValue:0,
				    	listeners: {
			        		change : {
			        			fn:this.checkAdmin,
			        			scope:this
			        		}
			        	}	
				    },{			    	
						displayField:"title",
						valueFiel:'id',
						queryMode:"remote",
						triggerAction:"all",
						valueField:"id",
						allowBlank: false,
						fieldLabel:"Group",
						name:"group_id",
						xtype:"combo",
						hidden:true,
						//disabled:true,
						forceSelection:true,	
						autoShow :true,
						store:this.groupsStore 	    	
				    },{
						allowBlank: false,
						fieldLabel:"Name",
						name:"name",
						xtype:"textfield"
					},{
						allowBlank: false,
						fieldLabel:"Login",
						name:"login",
						xtype:"textfield",
						validateOnBlur:false,
						vtype:"alphanum",
						enableKeyEvents:true,
						listeners:{
							keyup : {
								 fn: this.checkLogin,
								 scope:this,
								 buffer:400
							}
						}
					},{
						allowBlank: false,
						fieldLabel:"E-mail",
						name:"email",
						vtype:"email",
						xtype:"textfield",
						enableKeyEvents:true,
						listeners:{
							keyup : {
								 fn: this.checkMail,
								 scope:this,
								 buffer:400
							}
						}
						
					},{
						fieldLabel:"Enabled",
						id:"confirmedField",
						name:"enabled",
						xtype:"checkbox",
						inputValue:1,
				    	uncheckedValue:0
					},{
				    	name: 'setpass',
			        	value: 1,
			        	readOnly:true,
			        	fieldLabel: 'Change password',
			        	submitValue:false,
			        	checked:true,
			        	readOnly:true,
			        	xtype:'checkbox',
			        	listeners: {
			        		change : {
			        			fn:this.denyBlankPassword,
			        			scope:this,
			        			buffer:350
			        		}
			        	}
				    },{
						fieldLabel:"New password",
						inputType:"password",
						name:"pass",
						xtype:"textfield",
						enableKeyEvents:true,
						allowBlank:false
					},{
						fieldLabel:"Password confirmation",
						inputType:"password",
						name:"pass2",
						submitValue:false,
						xtype:"textfield",
						enableKeyEvents:true,
						vtype: 'password',
                		initialPassField: 'pass',
                		allowBlank:false
					}
		  ]
		});
		
		this.buttons =[
		   {
        	   text:'Cancel',
        	   listeners:{
	           		 click:{
	           			 fn:this.close,
	           			 scope:this
	           		 }
           	 	}
           },{
	           	 text:'Save',
	           	 listeners:{
		           		 click:{
		           			 fn:this.saveAction,
		           			 scope:this
		           		 }
	           	 }
           }
		];
		
		
		this.items=[this.dataForm];

		app.crud.user.Window.superclass.initComponent.call(this);
		
		this.addEvents(
            /**
             * @event dataSaved
             */
           'dataSaved'
		);  

		if(this.recordId){
			this.on('show' , function(){
				var handle = this.dataForm.getForm();
				this.dataForm.getForm().load({
					url:app.root + 'userload',
					params:{id:this.recordId},
					waitMsg:'Saving...',
					success: function(form, action){							
		   		 		handle.findField('setpass').enable();
		   				handle.findField('setpass').setValue(false);
		   		 		handle.findField('setpass').setReadOnly(false);	
					},
		   	        failure: app.formFailure
				});				
			},this);
			
			this.denyBlankPassword(null,false);
		}
	},
	/**
	 * Permit or rapretit be empty password field
	 * @param {Ext.form.field} field
	 * @param boolean bool
	 */
	denyBlankPassword:function(field, bool){
		var handle = this.dataForm.getForm();
		
		if(!bool){
			handle.findField('pass').disable();
			handle.findField('pass2').disable();
		} else {
			handle.findField('pass').enable();
			handle.findField('pass2').enable();
		}
		
		handle.findField('pass').allowBlank = !bool;
		handle.findField('pass2').allowBlank = !bool;
	},
	/**
	 * Save rule action
	 */
	saveAction:function(){
		var handle = this;
		this.dataForm.getForm().submit({
			clientValidation: true,	
			waitMsg:'Saving...',
			method:'post',
			url:app.root + 'usersave',
			success: function(form, action) {	
   		 			handle.fireEvent('dataSaved');
		 			handle.close(); 
   	        },
   	        failure: app.formFailure
   	    });
	},
	/**
	 * Mark user as system 
	 * @param {Ext.field.Checkbox} cmp - component
	 * @param boolean checked - status
	 * @returns void
	 */
	checkAdmin: function(cmp , checked){
		if(checked){
			this.dataForm.getForm().findField('group_id').show();
			this.dataForm.getForm().findField('group_id').enable();
		}else{
			this.dataForm.getForm().findField('group_id').hide();
			this.dataForm.getForm().findField('group_id').disable();
		}
	},
	/**
	 * check pass action
	 * @param {Ext.field.Checkbox} cmp - component
	 * @param boolean checked - status
	 * @returns void
	 */
	checkPass: function(cmp , checked){

		if(checked){
			this.dataForm.getForm().findField('pass').enable();
			this.dataForm.getForm().findField('pass2').enable();
		}else{
			this.dataForm.getForm().findField('pass').disable();
			this.dataForm.getForm().findField('pass2').disable();
		}
	},
   /**
    * Validate unique Login
    * @param {Ext.form.Field} field
    * @param {Event} event
    */
   checkLogin:function(field){
   		var val = field.getValue();
		var e = field.up('form').getForm().findField('id').getValue();
	   
		Ext.Ajax.request({
			url: app.root + "checklogin",
		 	method: 'post',
		 	params:{
		 		'id':e,
		 		'value':val
		 	},
			success: function(response, request) {
				response =  Ext.JSON.decode(response.responseText);
			 	if(response.success){
					field.unsetActiveError();
			 		field.clearInvalid();
			 	}else{
			 		field.markInvalid(response.msg);
			 		field.setActiveError(response.msg);
			 	}	
			},
			failure:app.formFailure
		});
   },
   /**
    * Validate unique email
    * @param {Ext.form.Field} field
    * @param {Event} event
    */
   checkMail:function(field , event){
		 var val = field.getValue(); 
		 Ext.Ajax.request({
		 		url: app.root + "checkemail",
		 		method: 'post',
		 		params:{
		 			'id':this.dataForm.getForm().findField('id').getValue(),
		 			'value':val
		 		},
		        success: function(response, request) {
		 			response =  Ext.JSON.decode(response.responseText);
		 			if(response.success){
		 				field.unsetActiveError();
		 				field.clearInvalid();
		 			}else{
		 				field.markInvalid(response.msg);
		 				field.setActiveError(response.msg);
		 			}	
		       },
		       failure:app.formFailure
		  });
    }
});


/**
 * Permissions pannel allows to modify users and groups permissions
 *  {Ext.Panel}
 */
Ext.define('app.crud.user.Permissions',{ 
	extend:'Ext.Panel',
	/**
	 * @var {Ext.grid.EditorGridPanel}
	 */
	dataGrid:null,
	/**
	 * @var {Ext.data.JsonStore}
	 */
	dataStore:null,

	initComponent:function(){
		
		this.dataStore = Ext.create('Ext.data.Store', {
		    model: 'app.crud.user.PermissionsModel',
		    proxy: {
		        type: 'ajax',
		        reader: {
		            type: 'json',
		            root: 'data',
		            idProperty: 'id'
		        },
		        writer:{
		        	type:'json',
					writeAllFields:true,
				    encode: true,   
				    listful:true,
				    root:'data'
			    },
		        extraParams:{
		        	'user_id':0,
					'group_id':0
		        },
		        method:'post',
				url: app.root + 'permissions',
			    api: {
			        create  :app.root + 'savepermissions',
			        update  : app.root + 'savepermissions'
			    },
			    simpleSortMode: true
		    },
		    sorters: [{
                property : 'module',
                direction: 'ASC'
          }]
		});
		
		 var cellEditing = Ext.create('Ext.grid.plugin.CellEditing', {
		        clicksToEdit: 1
		  });
		 
		this.dataGrid = new Ext.grid.Panel({
		  store: this.dataStore,
		  viewConfig:{
			  stripeRows:true
		  },
		  frame: false,
	      loadMask:true,
		  columnLines: true,
		  autoScroll:true,
		  clicksToEdit:1,
		  selModel: {
	            selType: 'cellmodel'
	      },
		  columns:[
				     {
						  text:'Module',
						  dataIndex:'module',
						  align:'left',
						  renderer:false,
						  editable:false,
						  id:'module',
						  width:200
				   },{
					   	  text:'All',
					   	  dataIndex:'id',
					   	  id:'all',
					   	  width:30,
					   	  scope:this,
					   	  renderer:function(value, metaData, record, rowIndex, colIndex, store){
					   	      var allChecked = this.checkPermissionsCol(record);
							  if(allChecked)
							  	  return '<img src="/js/lib/extjs4/resources/themes/images/default/menu/checked.gif">';
				   			  else
				   				  return '<img src="/js/lib/extjs4/resources/themes/images/default/menu/unchecked.gif">';		
					   	  }
				   },{
					   text:'View',
		        	   dataIndex:'view',
		        	   align:'center',
		        	   renderer:app.checkboxRenderer,
		        	   xtype:'checkcolumn'
		           },{
		        	   text:'Edit',
		        	   dataIndex:'edit',
		        	   align:'center',
		        	   renderer:app.checkboxRenderer,
		        	   xtype:'checkcolumn'
			       },{
			    	   text:'Delete',
			           dataIndex:'delete',
			           align:'center',
		        	   renderer:app.checkboxRenderer,
		        	   xtype:'checkcolumn'
			       },{
			    	   text:'Publish',
			           dataIndex:'publish',
			           id:'publish',
			           align:'center',
			           width:45,
			           xtype:'checkcolumn',
			           renderer:function(value, metaData, record, rowIndex, colIndex, store){			        	   
			        	   if(record.get('rc'))
			        			return app.checkboxRenderer(value, metaData, record, rowIndex, colIndex, store);
			        		else
			        			return '-';
			           }
			       }],
			       plugins: [cellEditing]
			       
	  });
		this.dataGrid.on('cellclick',function(grid, cell, columnIndex, record , node , rowIndex , evt){
			  var column = grid.getHeaderCt().getHeaderAtIndex(columnIndex).id;
			  
			  switch(column){
			  		case 'all':
			  			var allChecked = this.checkPermissionsCol(record);
			  			if (!allChecked){
			  				record.set('view' , true);
			  				record.set('edit' , true);
			  				record.set('delete' , true);
			  				
			  				if(record.get('rc')){
				  				record.set('publish' , true);
				  			}
			  			}else{
			  				record.set('view' , false);
			  				record.set('edit' , false);
			  				record.set('delete' , false);
			  				
			  				if(record.get('rc')){
				  				record.set('publish' , false);
				  			}
			  			}
			  			return false;
			  			break;
			  		case 'publish':
			  			if(!record.get('rc'))
			  				return false;
			  			break;		
			  }	        			
		},this);
		
	  if(app.crud.user.canEdit){
			this.buttons =[{
				 text:'Save',
				 listeners:{
						 click:{
							 fn:this.savePermissions,
							 scope:this
						 }
				 }
			}];
	  }
	  
	  this.items=[this.dataGrid];
	  
	  this.callParent(arguments);
	},
	
	checkPermissionsCol:function(record){
		var toCheck = ['view','edit','publish','delete'];
	 	var allChecked = true;
	  	Ext.each(toCheck , function(item){
			if(item !='publish'){
				if(!record.get(item)){
					allChecked = false;
				}
	  		}
		  
		  	if(item=='publish' && record.get('rc')){
				if(!record.get(item)){
   					allChecked = false;
   			  	}  
		  	}
		 },this);
		 return allChecked;
	},
	
	savePermissions: function(){
		this.dataStore.sync();
	}
});

app.crud.user.Groups = Ext.extend(Ext.Panel,{

	dataGrid:null,
	dataStore:null,
	permissionsPanel:null,
	
	constructor: function(config) {
		config = Ext.apply({
			modal: true,
			layout: {
			    type: 'hbox',
			    pack: 'start',
			    align: 'stretch'
			},
	        title: 'User groups'
	    }, config);		
		
		this.callParent(arguments);
	},
	
	initComponent:function(){
		

		this.dataStore = Ext.create('Ext.data.Store', {
		    model: 'app.crud.user.GroupModel',
		    proxy: {
		        type: 'ajax',
		        url: app.root + 'grouplist',
		        reader: {
		            type: 'json',
		            root: 'data',
		            totalProperty: 'count',
		            idProperty: 'id'
		        },
		        startParam:'pager[start]',
		        limitParam:'pager[limit]',
		        sortParam:'pager[sot]',
		        dirParam:'pager[dir]',
		        simpleSortMode: true
		    },
		    pageSize: 50,
	        remoteSort: true,
		    autoLoad: true,
		    sorters: [{
                 property : 'title',
                 direction: 'ASC'
           }]
		});
		
		this.dataGrid = Ext.create('Ext.grid.Panel',{
			  store: this.dataStore,	
			  viewConfig:{
				  stripeRows:true
			  },
		      loadMask:true,
			  columnLines: true,
			  autoScroll:true,
			  frame: false,
			  width:300,
			  columns:[
			           {
			        	  title:'Group Name',
			        	  dataIndex:'title',
			        	  align:'left',
			        	  flex:1
			           },{
			        	  header:'System',
			        	  dataIndex:'system',
			        	  align:'center',
			        	  width:60,
			        	  renderer:app.checkboxRenderer
				       },{
				    	  title:'',
				    	  dataIndex:'id',
				    	  id:'deleteColumn',
				    	  width:30,
				    	  align:'center',
				    	  renderer:function(value, metaData, record, rowIndex, colIndex, store){
				    		  	if(!app.crud.user.canDelete)
				    	   			return '';
				    	   		
				    	   		if(record.get('system')==true){
				    	   			return '';
				    	   		}else{
				    	   			return '<img src="/i/system/delete.gif" style="cursor:pointer;" title="Delete item">';
				    	   		}
				    	   	}
				       }
			   ]
		  }); 
		
		 this.permissionsPanel =  new app.crud.user.Permissions({
			 flex:1,
			 frame:false,
			 border:false
		 });

		 if(app.crud.user.canEdit){
			 this.tbar=[{
				 text:'Add Group',
				 listeners:{
					 click:{
						 fn:this.addGroup,
						 scope:this
					 }
				 }
			 }];
			 /**
			  * @todo fix event
			  */
			 this.dataGrid.on('cellclick',function(grid, cell, columnIndex, record , node , rowIndex , evt){
				  var column = grid.getHeaderCt().getHeaderAtIndex(columnIndex).id;
				  if(column =='deleteColumn'){
					  this.removeGroup(record.get('id'));
				  }else{
					  this.dataGrid.getSelectionModel().select(rowIndex , false);
					  this.groupSelected(rowIndex , record);
				  }
			},this);
		 }
		 
		 this.items=[this.dataGrid,this.permissionsPanel];
	 	 this.callParent(arguments);
	},
	
	groupSelected: function(rowIndex , record){	
		var store = this.permissionsPanel.dataStore;	
		this.permissionsPanel.setTitle('"'+record.get('title')+'" group permissions');
		store.proxy.extraParams['group_id']= record.get('id');
		store.proxy.extraParams['user_id']=  0;
		store.removeAll();
		store.load();
	},
	
	addGroup:function(){
		var handle = this;
		Ext.Msg.prompt('Message', 'Please enter new group name' , function(btn , text){
			if(btn != 'ok' || !text.length){
				return
			}
			 Ext.Ajax.request({
		 		url: app.root + "addgroup",
		 		method: 'post',
		 		params:{
		 			'name':text
		 		},
		        success: function(response, request) {
		 			response =  Ext.JSON.decode(response.responseText);
		 			if(response.success){
		 				handle.dataStore.load();
		 			}else{
		 				Ext.Msg.alert(response.msg);
		 			}	
		       },
		       failure:app.formFailure
			 });
			
		});
	},
	
	removeGroup: function(id){
		var handle = this;
		Ext.Ajax.request({
	 		url: app.root + "removegroup",
	 		method: 'post',
	 		params:{
	 			'id':id
	 		},
	        success: function(response, request) {
	 			response =  Ext.JSON.decode(response.responseText);
	 			if(response.success){
	 				handle.dataStore.load();
	 			}else{
	 				Ext.Msg.alert(response.msg);
	 			}	
	       },
	       failure:app.formFailure
		 });
	}
});

Ext.onReady(function(){
	Ext.QuickTips.init();
	app.crud.user.canEdit = canEdit;
	app.crud.user.canDelete = canDelete;
	app.content.add(Ext.create('app.crud.user.Main'));
});